package cn.usian.controller;

import cn.usian.common.R;
import cn.usian.entity.Employee;
import cn.usian.service.EmployeeService;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    /**
     * 作用登录
     * */
    @PostMapping("/login")
    public R<Employee>login(@RequestBody Employee employee, HttpSession session){
        R<Employee>r=employeeService.login(employee);
        //说明成功
        if(r.getCode()==1){
            //将用户编号保存在session中
            session.setAttribute("employee",r.getData().getId());
        }
        return r;
    }
    /**
     * 退出
     *
     * */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        //清除session
        session.invalidate();
        return R.success("退出成功");
    }

    @GetMapping("/page")
    public R<Page<Employee>>page(Integer page,Integer pageSize,String name){
        return employeeService.page(page,pageSize,name);
    }
    /*
    * 添加
    * */
    @PostMapping()
    public R save(@RequestBody Employee employee,HttpSession session){
        long id=(long)session.getAttribute("employee");
        //将创建者得id保存employee对象中
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        employeeService.save(employee);
        return R.success("添加成功");
    }
    /**
     * 修改
     * @param employee
     * @return
     */
    @PutMapping
    public R updateEmp(@RequestBody Employee employee,HttpSession session){
        Long id = (Long) session.getAttribute("employee");
        employee.setUpdateUser(id);
        employeeService.updateEmp(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询数据 进行回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){

        return employeeService.findById(id);
    }
}
